<template>
  <div class="page-content">
    <div>
      <el-button @click="gotoMall" type="primary">进入采购商城</el-button>
    </div>
    <br />
    <table-search
      ref="tableSearch"
      title="采购单列表"
      :columns="columns"
      :api="getList"
      selection
      @selection-change="onSelectionChange"
    >
      <div slot="table-title" class="table-title">
        <el-button
          size="medium"
          type="primary"
          plain
          :disabled="!selection.length"
          @click="onExportExcel"
        >导出所选列表{{selection.length ? `(${selection.length})` : ''}}</el-button>
      </div>

      <template #paymentPrice="{ row }">
        <span class="red">{{ formatAmount(row.paymentPrice) }}</span>
      </template>
      <template #orderState="{ row }">
        <span :class="{ green: row.orderState === 99 }">
          {{orderStateMap[row.orderState]}}
        </span>
        <template v-if="row.orderState === 99 && (row.refund === 2 || row.refund === 3)">
          <br />
          <span>(已退款)</span>
        </template>
      </template>

      <template #relateOrderIds="{ row }">
        <template v-if="!row.relateOrderIds">
          未关联
        </template>
        <el-popover
          v-else
          v-for="(text, index) in row.relateOrderIds.split(',')"
          :key="index"
          placement="top"
          trigger="hover"
          :content="text"
        >
          <el-tag
            slot="reference"
            size="mini"
            style="margin: 3px;max-width: 100%;overflow: hidden;text-overflow: ellipsis;"
          >
            {{text}}
          </el-tag>
        </el-popover>
      </template>

      <template #operate="{ row }">
        <el-link type="primary" @click="$router.push(`online/detail/${row.purchaseNo}`)">查看详情</el-link>
        <el-link
          type="primary"
          @click="onRelateOrder(row)"
        >关联订单号</el-link>
      </template>
    </table-search>
  </div>
</template>

<script>
import TableSearch from '@/components/TableSearch/TableSearch';
import { createTableColumns } from '@/components/TableSearch/utils';
import { orderStateMap, payTypeMap } from '@/config/purchase/online';
import { pageList, exportUrl, relateOrderEdit } from '@/api/purchase/onlineOrder';

export default {
  components: { TableSearch },

  data () {
    const { formatDate, formatAmount, map2Select } = this.$util;

    return {
      columns: createTableColumns([
        [
          '下单时间',
          'orderTime',
          {
            search: { key: 'startTime,endTime', sort: 9 },
            formatter: (val) => formatDate(val),
          },
        ],
        ['采购单号', 'purchaseNo', { search: true }],
        // ['采购商用户名', 'purchaseName'],
        ['供应商店铺', 'shopName', { search: true }],
        ['应付总金额（元）', 'paymentPrice', { align: 'right' }],
        ['支付方式', 'payType', { search: map2Select(payTypeMap), formatter: val => payTypeMap[val] }],
        ['订单状态', 'orderState', { search: map2Select(orderStateMap) }],
        ['关联订单号', 'relateOrderIds', { search: true, formatter: val => val ? val.split(',').join('\n') : '未关联' }],
        ['操作', 'operate'],
      ]),
      selection: [],
      formatAmount,
      orderStateMap,
    };
  },

  methods: {
    async getList (pageIndex, pageSize, query) {
      const newQuery = {
        pageIndex,
        pageSize,
        ...query,
      };
      return await pageList(newQuery);
    },

    onSelectionChange (val) {
      this.selection = val;
    },

    onExportExcel () {
      if (!this.selection.length) {
        this.$message.error('请选择要导出的记录');
        return;
      }
      this.$util.downloadFile(`${exportUrl}?purchaseNos=${this.selection.map(item => item.purchaseNo).join(',')}`);
    },

    onRelateOrder (row) {
      this.$prompt('多个订单号之间以英文逗号分隔', '关联订单号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.relateOrderIds || '',
        inputPlaceholder: '请输入关联订单号',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            // instance.confirmButtonText = '关联中...';
            try {
              await relateOrderEdit({
                purchaseNo: row.purchaseNo,
                relateOrderIds: instance.inputValue,
              });
              this.$message.success('关联成功');
              this.$refs.tableSearch.reload();
              done();
            } catch (error) {
            }
            instance.confirmButtonLoading = false;
          } else {
            done();
          }
        },
      });
    },

    gotoMall () {
      window.open('//www.tlwok.com/act/1004367');
    },
  },
};
</script>

<style scoped lang="scss">
.table-title {
  flex: 1;
  text-align: right;
  margin: -10px 0;
}
.red {
  color: #e30000;
}
.green {
  color: #06b62d;
}
</style>
